package api // 初始化模块路由
import (
	"fmt"
	"github.com/fatih/color"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"io/ioutil"
	"os/exec"
	"path"
	"path/filepath"
	"strconv"
	"strings"
	"web-collect-server/entity/common/response"
	"web-collect-server/entity/model"
	"web-collect-server/global"
)

type TreeParams struct {
	Path string `json:"path" form:"path"` // 路径 (params 必加 form)
}

var (
	count uint
)

func InitFolderRouter(r *gin.RouterGroup) {
	g := r.Group("/folder")
	g.GET("/tree", getTree)
	g.GET("/allFiles", getAllFiles)
	g.GET("/rootPath", getRootPath)
	g.GET("/baseFolder", getBaseFolder)
	g.GET("/capacityAndCount", getCapacityAndCount)
	g.GET("/capacityAndCount2", getCapacityAndCount2)
	g.GET("/capacityAndCount3", getCapacityAndCount3)
	g.GET("/capacityAndCount4", getCapacityAndCount4)
	g.POST("/setFolder", setFolder)
}

// 获取 话单容量 和 数量  map_nonip_cdr 已采集非IP话单
func getCapacityAndCount(c *gin.Context) {
	// 数据库先找到最后一个
	var folder model.Folder
	global.DB.Last(&folder)
	basePath := folder.Path
	if basePath == "" {
		response.FailWithMessage("获取话单容量和数量时没有找到 基础路径", c)
		return
	}
	//
	dapMapPath := path.Join(basePath, "map_nonip_cdr")

	cmd1 := exec.Command("du", "-sh", dapMapPath)
	stdout1, err := cmd1.Output()
	if err != nil {
		sprintf := fmt.Sprintf("du -sh %+v", dapMapPath)
		s := fmt.Sprintf("执行 %+v 命令失败! err.Error() -> %+v", sprintf, err.Error())
		response.FailWithMessage(s, c)
		return
	}
	s1 := string(stdout1)

	files, _ := ioutil.ReadDir(dapMapPath)
	//fmt.Println(len(files))
	response.OkWithData(CmdRes{Str1: strings.Trim(s1, "\n"), Str2: strconv.Itoa(len(files))}, c)
}

// 获取 话单容量 和 数量  map_nonip_rawdata 已采集非IP原始数据
func getCapacityAndCount2(c *gin.Context) {
	// 数据库先找到最后一个
	var folder model.Folder
	global.DB.Last(&folder)
	basePath := folder.Path
	if basePath == "" {
		response.FailWithMessage("获取话单容量和数量时没有找到 基础路径", c)
		return
	}
	//
	dapMapPath := path.Join(basePath, "map_nonip_rawdata")

	cmd1 := exec.Command("du", "-sh", dapMapPath)
	stdout1, err := cmd1.Output()
	if err != nil {
		sprintf := fmt.Sprintf("du -sh %+v", dapMapPath)
		s := fmt.Sprintf("执行 %+v 命令失败! err.Error() -> %+v", sprintf, err.Error())
		response.FailWithMessage(s, c)
		return
	}
	s1 := string(stdout1)

	files, _ := ioutil.ReadDir(dapMapPath)
	//fmt.Println(len(files))
	response.OkWithData(CmdRes{Str1: strings.Trim(s1, "\n"), Str2: strconv.Itoa(len(files))}, c)
}

// 获取 话单容量 和 数量  map_ip_cdr 已采集IP话单
func getCapacityAndCount3(c *gin.Context) {
	// 数据库先找到最后一个
	var folder model.Folder
	global.DB.Last(&folder)
	basePath := folder.Path
	if basePath == "" {
		response.FailWithMessage("获取话单容量和数量时没有找到 基础路径", c)
		return
	}
	//
	dapMapPath := path.Join(basePath, "map_ip_cdr")

	cmd1 := exec.Command("du", "-sh", dapMapPath)
	stdout1, err := cmd1.Output()
	if err != nil {
		sprintf := fmt.Sprintf("du -sh %+v", dapMapPath)
		s := fmt.Sprintf("执行 %+v 命令失败! err.Error() -> %+v", sprintf, err.Error())
		response.FailWithMessage(s, c)
		return
	}
	s1 := string(stdout1)

	files, _ := ioutil.ReadDir(dapMapPath)
	//fmt.Println(len(files))
	response.OkWithData(CmdRes{Str1: strings.Trim(s1, "\n"), Str2: strconv.Itoa(len(files))}, c)
}

// 获取 话单容量 和 数量  map_ip_rawdata 已采集IP话单
func getCapacityAndCount4(c *gin.Context) {
	// 数据库先找到最后一个
	var folder model.Folder
	global.DB.Last(&folder)
	basePath := folder.Path
	if basePath == "" {
		response.FailWithMessage("获取话单容量和数量时没有找到 基础路径", c)
		return
	}
	//
	dapMapPath := path.Join(basePath, "map_ip_rawdata")

	cmd1 := exec.Command("du", "-sh", dapMapPath)
	stdout1, err := cmd1.Output()
	if err != nil {
		sprintf := fmt.Sprintf("du -sh %+v", dapMapPath)
		s := fmt.Sprintf("执行 %+v 命令失败! err.Error() -> %+v", sprintf, err.Error())
		response.FailWithMessage(s, c)
		return
	}
	s1 := string(stdout1)

	files, _ := ioutil.ReadDir(dapMapPath)
	//fmt.Println(len(files))
	response.OkWithData(CmdRes{Str1: strings.Trim(s1, "\n"), Str2: strconv.Itoa(len(files))}, c)
}

// 获取基础 folder
func getBaseFolder(c *gin.Context) {
	// 数据库先找到最后一个
	var folder model.Folder
	global.DB.Last(&folder)
	var count int64
	// 获取 folder 表的 数据 数量
	global.DB.Model(&model.Folder{}).Count(&count)
	if count == 0 {
		response.FailWithMessage("请先选择目录", c)
		return
	}
	response.OkWithData(folder, c)
}

// 获取基本路径
func getRootPath(c *gin.Context) {
	settings := global.Settings
	response.OkWithData(settings, c)
}

// 获取文件夹树
func getTree(c *gin.Context) {
	var settings TreeParams
	_ = c.ShouldBindQuery(&settings)
	folderName := settings.Path
	folders, err := ioutil.ReadDir(folderName)
	folderList := []model.Folder{}

	if err == nil {
		for _, file := range folders {
			if file.IsDir() {
				u := uuid.New()
				folderList = append(folderList, model.Folder{OwnId: u, Path: path.Join(folderName, file.Name()), Name: file.Name()})
			}
		}
	}
	response.OkWithData(folderList, c)
}

// 设置根目录
func setFolder(c *gin.Context) {
	var folder model.Folder
	err := c.ShouldBindJSON(&folder)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	color.Blue("folder.path -> %+v", folder.Path)
	global.DB.Create(&folder)
	response.OkWithData(folder, c)
}

// 获取所有文件
func getAllFiles(c *gin.Context) {
	// 数据库先找到最后一个
	var folder model.Folder
	global.DB.Last(&folder)
	path := folder.Path
	color.Blue("path -> %+v", path)
	newId := uuid.New()
	var folders []model.Folder
	folders = append(folders, model.Folder{OwnId: newId, Path: path, Name: folder.Path})
	recSearch(path, c, newId, &folders)
	response.OkWithData(folders, c)
}

func recSearch(path string, c *gin.Context, id uuid.UUID, folders *[]model.Folder) {
	files, err := ioutil.ReadDir(path)
	if err == nil {
		for _, file := range files {
			name := file.Name()
			newId := uuid.New()
			// 修改指针里面的列表
			*folders = append(*folders, model.Folder{Path: filepath.Join(path, name), Name: name, OwnId: newId, PId: id, IsLeaf: !file.IsDir(), Size: file.Size()})
			count++
			if file.IsDir() {
				recSearch(filepath.Join(path, name), c, newId, folders)
			}
		}
	} else {
		response.FailWithMessage(err.Error(), c)
	}

}
